package com.suishoupai.xmb.service;

import com.suishoupai.xmb.dao.CutSearchMapper;
import com.suishoupai.xmb.dao.CutXiaoquMapper;
import com.suishoupai.xmb.dao.SearchMapper;
import com.suishoupai.xmb.dao.XiaoquMapper;
import com.suishoupai.xmb.entity.*;
import com.suishoupai.xmb.utils.ParticipleUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by caojian on 2017/3/30.
 */
@Service
public class XiaoquService {
    @Autowired
    private XiaoquMapper xiaoquMapper;
    @Autowired
    private CutXiaoquMapper cutXiaoquMapper;
    @Autowired
    private SearchMapper searchMapper;
    @Autowired
    private CutSearchMapper cutSearchMapper;

    public List<Xiaoqu> getAll() {
        return cutXiaoquMapper.selectAll();
    }

    public Xiaoqu getByXiaoquId(long xiaoquId) {
        return cutXiaoquMapper.selectByPrimaryKey(xiaoquId);
    }

    public void add(Xiaoqu xiaoqu) {
        xiaoqu.setCreateTime(System.currentTimeMillis());
        if (xiaoquMapper.insertSelective(xiaoqu) == 0) {
            throw new RuntimeException("插入失败！");
        }
        Search search = new Search();
        search.setDid(xiaoqu.getId());
        search.setType(SearchTypeEnum.XIAOQU.getValue());
        search.setName(ParticipleUtil.participle(xiaoqu.getName()));
        if (searchMapper.insert(search) == 0) {
            throw new RuntimeException("插入失败！");
        }
    }

    @Transactional
    public void update(Xiaoqu xiaoqu) {
        if (cutXiaoquMapper.updateByPrimaryKeySelective(xiaoqu) == 0) {
            throw new RuntimeException("更新失败！");
        }
        if (xiaoqu.getName() != null) {
            Search search = new Search();
            search.setDid(xiaoqu.getId());
            search.setType(SearchTypeEnum.XIAOQU.getValue());
            search.setName(ParticipleUtil.participle(xiaoqu.getName()));
            if (cutSearchMapper.updateByPrimaryKeySelective(search) == 0) {
                throw new RuntimeException("更新失败！");
            }
        }
    }

    /**
     * 筛选位置
     *
     * @return
     */
    public List<Xiaoqu> filterLocation(Location center) {
        double latitude = center.getLatitude();
        double longitude = center.getLongitude();
        double dx = 0.1;
        LocationFilter locationFilter = new LocationFilter();
        locationFilter.setMaxLatitude(latitude + dx);
        locationFilter.setMinLatitude(latitude - dx);
        locationFilter.setMaxLongitude(longitude + dx);
        locationFilter.setMinLongitude(longitude - dx);
        List<Xiaoqu> xiaoqus = cutXiaoquMapper.filterLocation(locationFilter);
        return xiaoqus;
    }
}
